import cv2
import numpy as np
import cv2
import numpy as np
class ColorDetector:
    """颜色检测器，用于识别图像中的特定颜色区域"""

    COLOR_RANGES = {
        'blue': ([85, 43, 46], [100, 255, 255]),
        'red': [
            ([0, 150, 50], [10, 255, 255]),
            ([160, 150, 50], [180, 255, 255])
        ],
        'green': ([35, 43, 46], [77, 255, 255]),
        'yellow': ([26, 43, 46], [34, 255, 255]),
        'orange': ([10, 150, 50], [25, 255, 255]),
        'purple': ([125, 43, 46], [150, 255, 255]),
        'pink': ([145, 43, 46], [160, 255, 255]),
        'gray': ([0, 0, 50], [180, 50, 200])
    }

    def __init__(self, image):
        """初始化颜色检测器

        Args:
            image: 输入BGR图像
        """
        self.image = image
        self.hsv = cv2.cvtColor(self.image, cv2.COLOR_BGR2HSV)
        self.kernel = np.ones((5, 5), np.uint8)

    def _process_mask(self, mask):
        """对mask进行后处理（开运算和闭运算）

        Args:
            mask: 原始颜色mask

        Returns:
            处理后的mask
        """
        mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, self.kernel)
        mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, self.kernel)
        return mask

    def detect_color(self, color_name):
        """检测特定颜色区域

        Args:
            color_name: 颜色名称（blue/red/green/yellow）

        Returns:
            该颜色的mask
        """
        if color_name not in self.COLOR_RANGES:
            raise ValueError(f"Unsupported color: {color_name}")

        color_range = self.COLOR_RANGES[color_name]

        if color_name == 'red':
            # 红色需要特殊处理（两个区间）
            lower1, upper1 = color_range[0]
            lower2, upper2 = color_range[1]
            mask1 = cv2.inRange(self.hsv, np.array(lower1), np.array(upper1))
            mask2 = cv2.inRange(self.hsv, np.array(lower2), np.array(upper2))
            mask = cv2.bitwise_or(mask1, mask2)
        else:
            lower, upper = color_range
            mask = cv2.inRange(self.hsv, np.array(lower), np.array(upper))

        return self._process_mask(mask)

    def detect_all_colors(self):
        """检测所有支持的颜色区域

        Returns:
            合并所有颜色区域的mask
        """
        combined_mask = None

        for color in self.COLOR_RANGES.keys():
            mask = self.detect_color(color)
            if combined_mask is None:
                combined_mask = mask
            else:
                combined_mask = cv2.bitwise_or(combined_mask, mask)

        return combined_mask

    def show_colors_combined(self, color_names, window_name="Combined Colors"):
        """显示多个颜色的合成图像

        Args:
            color_names: 颜色名称列表(如['red', 'blue'])
            window_name: 窗口名称(可选)

        Returns:
            合成后的二值图像（白色表示检测到的颜色，黑色背景）
        """
        # 创建单通道的空白图像
        combined_binary = np.zeros(self.image.shape[:2], dtype=np.uint8)

        for color in color_names:
            if color not in self.COLOR_RANGES:
                print(f"警告: 忽略不支持的颜色 {color}")
                continue

            mask = self.detect_color(color)

            # 将当前颜色的mask合并到总结果中
            combined_binary = cv2.bitwise_or(combined_binary, mask)

        return combined_binary

    def cneter(self):
        height, width = self.image.shape[:2]
        center_x = width // 2
        center_y = height // 2
        return (center_x, center_y)


if __name__ == '__main__':
    # 测试代码
    image = cv2.imread('1.jpg')
    if image is None:
        print("无法加载图像，请检查路径")
        exit(1)

    detector = ColorDetector(image)

    # 检测各颜色
    masks = {
        color: detector.detect_color(color)
        for color in detector.COLOR_RANGES.keys()
    }
    combined_mask = detector.detect_all_colors()
    k=detector.detect_color('gray')
    i=detector.show_colors_combined(['red', 'blue', 'green'])
    j=detector.show_colors_combined(['yellow', 'purple', 'pink'])
    print(detector.cneter())
    cv2.imshow('Combined gray', k)
    # 显示结果
    cv2.imshow('Combined Colors', image)
    cv2.imshow('Combined ', i)
    cv2.imshow('Combi', j)

    cv2.waitKey(0)
    cv2.destroyAllWindows()

